package cn.huangyunxing.api.service.impl;

import cn.huangyunxing.api.common.ErrorCode;
import cn.huangyunxing.api.exception.BusinessException;
import cn.huangyunxing.api.mapper.UserInterfaceInfoMapper;
import cn.huangyunxing.api.service.UserInterfaceInfoService;
import cn.huangyunxing.common.model.entity.UserInterfaceInfo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.catalina.deploy.NamingResourcesImpl;
import org.apache.ibatis.executor.BaseExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @author HuangXing
 * @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
 * @createDate 2023-09-10 15:16:16
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {

    private NamingResourcesImpl transactionManager;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {

        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //创建时，所有参数必须为空
        if (add) {
            if (userInterfaceInfo.getInterfaceInfoId() <= 0 || userInterfaceInfo.getUserId() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或者用户不存在");
            }
        }

        if (userInterfaceInfo.getLeftNum() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数不能小于0");
        }
        if (userInterfaceInfo.getTotalNum() < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "使用次数不能小于0");
        }
        if (userInterfaceInfo.getStatus() == 1 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "已被禁用");
        }
    }

    @Override
    public boolean invokeCount(long interfaceId, long userId) {
        //判断
        if (interfaceId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        //todo 事务（"left_num = left_num - 1,total_num = total_num + 1"） 需要加锁
        updateWrapper.eq("interface_id", interfaceId)
                .eq("user_id", userId)
                .gt("left_num",0)
                .setSql("left_num = left_num - 1,total_num = total_num + 1");

        return this.update(updateWrapper);
    }
}




